package cn.ncu.wechat.controller;

import cn.ncu.wechat.service.OrdersService;
import cn.ncu.wechat.util.WeChatPayUtil;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.util.Map;

@RestController
public class WeChatPayController {
    @Value("${wx.app.apiKey}")
    private String apiKey;

    @Autowired
    private OrdersService ordersService;

    @PostMapping("/wechat/pay/notify")
    public String wechatPayNotify(HttpServletRequest request) throws Exception {
        // 读取请求体中的 XML 数据
        BufferedReader reader = request.getReader();
        StringBuilder xmlBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            xmlBuilder.append(line);
        }
        String xmlData = xmlBuilder.toString();

        // 解析 XML 数据
        XmlMapper xmlMapper = new XmlMapper();
        Map<String, String> responseParams = xmlMapper.readValue(xmlData, Map.class);

        // 验证签名
        if (WeChatPayUtil.isSignatureValid(responseParams, apiKey)) {
            // 处理支付结果
            String returnCode = responseParams.get("return_code");
            if ("SUCCESS".equals(returnCode)) {
                String orderNo = responseParams.get("out_trade_no");
                String transactionId = responseParams.get("transaction_id");
                String totalFee = responseParams.get("total_fee");

                // 更新订单状态
                String tradeState = responseParams.get("trade_state");
                switch (tradeState) {
                    case "SUCCESS":
                        // 支付成功，更新订单状态
                        ordersService.updateOrder(orderNo,2,false,null,responseParams.get("time_end"));
                        System.out.println("订单支付成功，订单号：" + orderNo + "，微信订单号：" + transactionId);
                        break;
                    case "REFUND":
                        // 转入退款，更新订单状态
                        ordersService.updateOrder(orderNo,4,false,null,null);
                        System.out.println("订单转入退款，订单号：" + orderNo);
                        break;
                    case "NOTPAY":
                        // 未支付，更新订单状态
                        ordersService.updateOrder(orderNo,1,false,null,null);
                        System.out.println("订单未支付，订单号：" + orderNo);
                        break;
                    case "CLOSED":
                        // 已关闭，更新订单状态
                        System.out.println("订单已关闭，订单号：" + orderNo);
                        break;
                    case "REVOKED":
                        // 已撤销，更新订单状态
                        System.out.println("订单已撤销，订单号：" + orderNo);
                        break;
                    case "USERPAYING":
                        // 用户支付中，更新订单状态
                        System.out.println("用户支付中，订单号：" + orderNo);
                        break;
                    case "PAYERROR":
                        // 支付失败，更新订单状态
                        System.out.println("支付失败，订单号：" + orderNo);
                        break;
                    default:
                        System.err.println("未知的交易状态：" + tradeState);
                        break;
                }

                // 返回成功响应
                return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            } else {
                // 支付失败
                String returnMsg = responseParams.get("return_msg");
                // 记录日志或处理失败逻辑
                // ...
                System.out.println("微信通知支付失败");
                // 返回失败响应
                return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[" + returnMsg + "]]></return_msg></xml>";
            }
        } else {
            // 签名验证失败
            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名验证失败]]></return_msg></xml>";
        }
    }
}
